import time

from django.db import models
from django.utils.translation import gettext_lazy as _
from django.db.models import Count, Sum, F
from api.utils.enums import BasketType, PriceType, OrderStatus

from api.models.order import Order, OrderLine


class Basket(models.Model):
    user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="basket")
    status = models.CharField(
        choices=BasketType.to_choices(), default=BasketType.PRE.value, max_length=256
    )
    date_merged = models.DateTimeField(_("Date merged"), null=True, blank=True, auto_now=True)
    date_submitted = models.DateTimeField(
        _("Date submitted"), null=True, blank=True, auto_now_add=True
    )

    def total_rmb(self):
        total = self.basket_lines.filter(pay_type=PriceType.RMB.value, choice=True).aggregate(
            sum_price=Sum(F("price") * F("quantity"))
        )
        return total.get("sum_price", 0)

    def total_point(self):
        total = self.basket_lines.filter(pay_type=PriceType.POINT.value).aggregate(
            sum_price=Sum(F("price") * F("quantity"))
        )
        return total.get("sum_price", 0)

    def make_order(self, address):
        if self.status == BasketType.PRE.value:
            raise ValueError("购物车状态错误")

        # 创建订单
        order = Order.objects.create(
            order_num=int(time.time()),
            user=self.user,
            address=address,
            status=OrderStatus.TO_BE_PAID.value,
            total_rmb=0 if self.total_rmb() is None else self.total_rmb(),
            total_point=0 if self.total_point() is None else self.total_point(),
        )

        if order:
            # 创建订单行
            for order_line in [
                OrderLine(
                    prodcut=basket_line.product,
                    order=order,
                    quantity=self.basket_lines.get(product=basket_line.product).quantity,
                    title=self.basket_lines.get(product=basket_line.product).product_title,
                    pirce=self.basket_lines.get(product=basket_line.product).quantity
                    * self.basket_lines.get(product=basket_line.product).price,
                )
                for basket_line in self.basket_lines.filter(basket=self, choice=True)
            ]:
                order_line.save()

        return order


class BasketLine(models.Model):
    product = models.ForeignKey("Porduct", on_delete=models.CASCADE, related_name="basket_lines")
    basket = models.ForeignKey("Basket", on_delete=models.CASCADE, related_name="basket_lines")
    quantity = models.PositiveIntegerField("数量", default=0)
    price = models.PositiveIntegerField("价格", default=0)
    pay_type = models.CharField(
        "支付类型", choices=PriceType.to_choices(), default=PriceType.RMB.value, max_length=256
    )
    choice = models.BooleanField("是否选择商品", default=True)

    @property
    def product_title(self):
        return self.product.title
